// #ifdef H5
import Cookies from 'js-cookie'
import {
	domain
} from '@/config'
// #endif

// 封装好本地存贮的方法，页面中使用方法 => this.$storage.get()
class storage {
	//存储在本地缓存指定的name中
	set(name, data) { 
		try {
			// #ifndef H5
			uni.setStorageSync(name, data);
			// #endif

			// #ifdef H5
			Cookies.set(name, data, {
				expires: 3,
				domain: domain('cookie')
			});
			// #endif
		} catch (e) {
			console.log(e)
		}
	}

	//从本地缓存中读取置顶name对应的内容
	get(name) {
		let data = null;
		try {
			// #ifndef H5
			data = uni.getStorageSync(name);
			// #endif

			// #ifdef H5
			try {
				data = JSON.parse(Cookies.get(name));
			} catch (e) {
				data = Cookies.get(name);
			}
			// #endif
		} catch (e) {
			console.log(e);
		}
		return data
	}

	//从本地缓存中移出指定key
	remove(name) {
		try {
			// #ifndef H5
			uni.removeStorageSync(name);
			// #endif

			// #ifdef H5
			Cookies.remove(name, {
				domain: domain('cookie')
			});
			// #endif
		} catch (e) {
			console.log(e);
		}
	}

	//返回一个布尔值,表示name是否在本地缓存之中
	check(name) {
		let value;
		let res;
		try {
			// #ifndef H5
			res = uni.getStorageSync(name)
			// #endif

			// #ifdef H5
			res = Cookies.get(name);
			// #endif
			
			value = res ? true : false

		} catch (e) {
			console.log(e)
		}
		return value
	}

	//清除本地数据缓存
	clear() {
		try {
			// #ifndef H5
			uni.clearStorageSync();
			// #endif

			// #ifdef H5
			const date = new Date();
			date.setTime(date.getTime() - 10000);
			//keys为所要删除cookie的名字
			const keys = document.cookie.match(/[^ =;]+(?=\=)/g);
			//删除所有cookie
			if (keys) {
				for (let i = keys.length; i--;)
					document.cookie = keys[i] + "=0; expire=" + date.toGMTString() + "; path=/";
			}
			// #endif
		} catch (e) {
			console.log(e)
		}
	}
}

export default new storage();
